package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1：查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2：组装成树形结构
        //2.1：找到素有的一级分类
        List<CategoryEntity> level1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                })
                .sorted(Comparator.comparingInt(item -> item.getSort() == null ? 0 : item.getSort()))
                .collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long attrGroupId) {
        List<Long> paths = this.findParentPath(attrGroupId, new ArrayList<>());
        //先添加的子节点再添加的父节点,我们需要的是[父,子,子],所以将集合中的数据翻转一下
        Collections.reverse(paths);
        //将集合转换为数组返回
        return paths.toArray(new Long[0]);
    }

    @Transactional  //添加事务注解
    @Override
    public void updateCascade(CategoryEntity category) {
        //级联更新所有关联的数据
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * 递归获取当前分类的父id添加到集合中
     *
     * @return
     */
    public List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);//先将当前节点添加到集合中
        //获取当前节点的父节点信息
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            //继续递归查询父节点信息
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        //查询到结果,返回
        return paths;

    }

    /**
     * 递归查找所有菜单的子类型
     *
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childList = all.stream()
                .filter(item -> item.getParentCid() == root.getCatId())
                .map(menu -> {
                    menu.setChildren(getChildren(menu, all));
                    return menu;
                })
                .sorted(Comparator.comparingInt(item -> item.getSort() == null ? 0 : item.getSort()))
                .collect(Collectors.toList());
        return childList;
    }

}